import axios from "axios";

const state = {};

const mutations = {
  SET_HISTORY: (state, { key, value, username, time }) => {
    if (state[key] == null) {
      state[key] = [];
    }
    state[key].push({ value, username, time });
  },
};

const actions = {
  saveHistory({ commit, rootGetters }, { key, value }) {
    axios
      .post("api/save_status/", {
        key,
        value,
        userbase: rootGetters.userbase,
        time: new Date().getTime(),
      })
      .then((response) => {
        console.log(response);
        commit;
      })
      .catch((error) => {
        console.log(error);
      });
    commit("SET_HISTORY", {
      key,
      value,
      username: rootGetters.userbase.name,
      time: new Date().getTime(),
    });
  },
  loadHistory({ commit }, { key, lastChange }) {
    return new Promise((resolve, reject) => {
      axios
        .post("api/load_status/", { key, lastChange })
        .then((response) => {
          if (response.data) {
            commit("SET_HISTORY", {
              key,
              value: response.data.value,
              username: response.data.username,
              time: response.data.time,
            });
            resolve(response.data);
          } else {
            console.log(response);
            resolve();
          }
        })
        .catch((error) => {
          console.log(error);
          reject(error);
        });
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
